package leetcode.code0498;

import leetcode.IDebug;
import leetcode.helper.H;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public int[] findDiagonalOrder(int[][] mat) {
		int m = mat.length, n = mat[0].length;
		if (m == 1) {
			return mat[0];
		}
		int[] ans = new int[m * n];
		int pans = 0;
		int x1 = 0, y1 = 0;
		int x2 = 1, y2 = 0;
		for (int i = 1; i < m + n; i++) {
			int size = i <= m ? Math.min(i, n) : Math.min(m + n - i, m);
			if ((i & 1) == 1) {
				for (int j = 0; j < size; j++) {
					ans[pans++] = mat[x1 - j][y1 + j];
				}
				if (x1 < m - 1) {
					x1 += 2;
					if (x1 >= m) {
						x1 = m - 1;
						y1 = 1;
					}
				} else {
					y1 += 2;
				}
			} else {
				for (int j = size - 1; j >= 0; j--) {
					ans[pans++] = mat[x2 - j][y2 + j];
				}
				if (x2 < m - 1) {
					x2 += 2;
					if (x2 >= m) {
						x2 = m - 1;
						y2 = 1;
					}
				} else {
					y2 += 2;
				}
			}
		}
		return ans;
	}

	@Override
	public void debug1() {
		H.compare(H.str2array3("[1,2,4,7,5,3,6,8,9]"),
				this.findDiagonalOrder(H.str2array1("[[1,2,3,10,15],[4,5,6,11,12],[7,8,9,13,14]]")));
		H.compare(H.str2array3("[1,2,4,7,5,3,6,8,9]"),
				this.findDiagonalOrder(H.str2array1("[[1,2,3],[4,5,6],[7,8,9]]")));

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
//		so.debug2();
//		so.debug3();
		so.debug4();
//		int[] ans = so.findDiagonalOrder(H.str2array1("[[1,2,3],[4,5,6],[7,8,9]]"));
//		H.printObject(ans);
		int[] ans = so.findDiagonalOrder(HelpDebug.str2array1("[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]"));
		HelpDebug.print(ans);

	}

}
